import { getWebPageProt } from "@/utils/default-util"

/**
 * 检查是否有文件更新 (会进行轮询)
 */
export const checkUpdateState = () => {
    return new Promise((resolve, reject) => {
        fetch(`/api/check-update-state?t=${new Date().getTime()}`)
            .then(response => response.json())
            .then(json => {
                resolve(json)
            })
            .catch(err => {
                reject(err)
            })
    })
}

/**
 * 检查是否在主机环境
 */
export const checkIsMasterHost = () => {
    return new Promise(async (resolve, reject) => {
        const port = getWebPageProt()
        try {
            const response = await fetch(`http://localhost:${port}/api/check-update-state`)    // 本地地址能访问则认为是主机
            const json = await response.json()
            if (json && json.code === 0) {
                resolve(true)
            } else {
                resolve(false)
            }
        } catch (e) {
            resolve(false)
        }
    })
}

/**
 * 文件列表
 */
export const getFileList = () => {
    return new Promise((resolve, reject) => {
        fetch(`/api/file-list?t=${new Date().getTime()}`)
            .then(response => response.json())
            .then(json => {
                resolve(json)
            })
            .catch(err => {
                reject(err)
            })
    })
}

/**
 * 文件上传
 */
export const onFileUpload = (files, progressCallback) => {
    return new Promise((resolve, reject) => {

        const formData = new FormData();
        for (let i = 0; i < files.length; i++) {
            formData.append(encodeURIComponent(files[i].name), files[i]);
        }

        // 使用fetch API发送POST请求到后端接口
        // fetch(`/api/file/upload`, {
        //     method: 'POST',
        //     body: formData
        // }).then(response => response.json()).then(result => {
        //     showUploadPopup.value = false
        //     refreshFileList()
        // }).catch(e => {
        //     console.log('e', e)
        // })

        var xhr = new XMLHttpRequest();
        xhr.open('POST', `/api/file-upload?t=${new Date().getTime()}`, true);
        xhr.upload.onprogress = (event) => {
            if (event.lengthComputable && progressCallback) {
                progressCallback(parseInt((event.loaded / event.total) * 100))
            }
        };
        xhr.onload = () => {
            if (xhr.status === 200) {
                resolve(xhr)
            } else {
                reject(xhr)
            }
        };
        xhr.send(formData);
    })
}

/**
 * 发送聊天文本
 */
export const onSendText = (text) => {
    return new Promise((resolve, reject) => {
        fetch(`/api/add-text?content=${text}&t=${new Date().getTime()}`)
            .then(response => response.json())
            .then(data => {
                resolve(data)
            }).catch(error => {
                reject(error)
            })
    })
}

/**
 * 直接读取文本文件的内容
 */
export const getTextValue = (text) => {
    return new Promise((resolve, reject) => {
        fetch(`/api/add-text?content=${text}&t=${new Date().getTime()}`)
            .then(response => response.json())
            .then(data => {
                resolve(data)
            }).catch(error => {
                reject(error)
            })
    })
}

/**
 * 删除选中文件
 */
export const onRemoveFiles = (encodeNames) => {
    return new Promise((resolve, reject) => {
        fetch(`/api/file-delete?names=${encodeNames}&t=${new Date().getTime()}`)
            .then(response => response.json())
            .then(data => {
                resolve(data)
            }).catch(error => {
                reject(error)
            });
    })
}

/**
 * 批量打包导出文件
 */
export const onPackageDownload = (encodeNames) => {
    return new Promise((resolve, reject) => {
        fetch(`/api/build-package-download?names=${encodeNames}&t=${new Date().getTime()}`)
            .then(response => response.json())
            .then(json => {
                resolve(json)
            }).catch(e => {
                reject(e)
            })
    })
}

/**
 * 读取文本
 */
export const onReadText = (url) => {
    return new Promise((resolve, reject) => {
        fetch(url)
            .then(response => response.text())
            .then(text => resolve(text))
            .catch(err => reject(err))
    })
}